import { reactive, toRefs } from 'vue'
import { defineStore } from 'pinia'

export const useLocationStore = defineStore('location', () => {
  const state = reactive({
    latitude: 0,
    longitude: 0
  })

  function getLocation() {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        success(res) {
          state.latitude = res.latitude
          state.longitude = res.longitude
          resolve(true)
        },
        fail(err) {
          uni.showModal({
            content: '获取地址失败，重新获取',
            success(res) {
              res.confirm && getLocation()
            }
          })
          reject(err)
        }
      })
    })
  }

  return {
    ...toRefs(state),
    getLocation
  }
})
